package com.yupi.yupicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.*;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yupi.yupicturebackend.config.ClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Deprecated
@Service
/**
 * 腾讯云对象存储工具类
 */
public class FileManger {
    @Autowired
    private CosUtils cosUtils;
    @Resource
    private ClientConfig clientConfig;
    //文件上传
    // 将本地文件上传到 COS
    public  UploadPictureResult putObject(MultipartFile file,String uploadpathPrefix) throws CosClientException {
        //对图片进校验
        checkPacture(file);
        //设置图片上传地址
        //uuid防止文件重复
        String uuid = RandomUtil.randomString(6);
        //文件名
        String pictureName = file.getName();
        String pathName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid,pictureName);
        String PicturePath = String.format("/%s/%s",uploadpathPrefix,pathName);
        //上传文件
        File tempFile = null;
        try {
            tempFile = File.createTempFile(PicturePath, null);
            file.transferTo(tempFile);
            PutObjectResult putObjectResult = cosUtils.putPictureObject(PicturePath, tempFile);
            if (putObjectResult == null) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
            }
            //对图片进行封装
            UploadPictureResult result = new UploadPictureResult();
            ImageInfo info = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //计算宽高
            int width = info.getWidth();
            int height = info.getHeight();
           double  scale = NumberUtil.round(width*1.0/height,2).doubleValue();

            result.setUrl(clientConfig.getHost() + PicturePath);
            result.setPicName(file.getName());
            result.setPicSize(file.getSize());
            result.setPicWidth(width);
            result.setPicHeight(height);
            result.setPicScale(scale);
            result.setPicFormat(info.getFormat());

            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (tempFile != null) {
                boolean delete = tempFile.delete();
                if (!delete) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件删除失败");
                }
            }
        }
    }
    public  void  checkPacture(MultipartFile file){
        //对象不能为空，如果为空返回异常
        if (file == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件不能为空");
        }
        //校验文件大小
       final long RuleSize = 1024*1024;
        long filesize = file.getSize();
        if(filesize > RuleSize){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小不能大于2M");
        }
        //校验文件格式
        final List<String> list = Arrays.asList("jdp","png");
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        if(!list.contains(suffix)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件格式错误");
        }
    }

    public  UploadPictureResult putObjectUrl(String Url,String uploadpathPrefix) throws CosClientException, MalformedURLException {
        //对图片进校验
        checkUrl(Url);
        //设置图片上传地址
        //uuid防止文件重复
        String uuid = RandomUtil.randomString(6);
        //文件名
        String pictureName = FileUtil.mainName(Url);
        String pathName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid,pictureName);
        String PicturePath = String.format("/%s/%s",uploadpathPrefix,pathName);
        //上传文件
        File file = null;
        try {
            file = File.createTempFile(PicturePath, null);
            HttpUtil.downloadFile(Url,file);
            PutObjectResult putObjectResult = cosUtils.putPictureObject(PicturePath, file);
            if (putObjectResult == null) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
            }
            //对图片进行封装
            UploadPictureResult result = new UploadPictureResult();
            ImageInfo info = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //计算宽高
            int width = info.getWidth();
            int height = info.getHeight();
            double  scale = NumberUtil.round(width*1.0/height,2).doubleValue();

            result.setUrl(clientConfig.getHost() + PicturePath);
            result.setPicName(file.getName());
            result.setPicSize(file.length());
            result.setPicWidth(width);
            result.setPicHeight(height);
            result.setPicScale(scale);
            result.setPicFormat(info.getFormat());

            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件删除失败");
                }
            }
        }
    }

    private void checkUrl(String url) throws MalformedURLException {
        //参数校验
        if(StrUtil.isBlank(url)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"url不能为空");
        }
        //校验url格式
        new URL(url);
        //校验url协议
        if(!url.startsWith("http") || !url.startsWith("https")){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"url格式错误");
        }
        //校验url是否存在
        HttpResponse response = HttpUtil.createRequest(Method.HEAD, url).execute();
        //not normal return
        if(response.getStatus() != HttpStatus.HTTP_OK){
            return;
        }
        //校验文本格式
        String header = response.header("Content-Type");
        List<String> ALLOWS_CONTENT_TYPES = Arrays.asList("image/jpeg","image/png");
        if(!ALLOWS_CONTENT_TYPES.contains(header)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图片格式错误");
        }
        //校验文件大小
        String filesize = response.header("Conent-Length");
        long length = Long.parseLong(filesize);
        final long RuleSize = 1024*1024;
        if(length > 2*RuleSize){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小不能大于2M");
        }
    }
}

